#pragma once
#include "MCommon.h"
#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <map>
#include <functional>
#include <string>
#include <vector>
// #include <QNetworkAccessManager>
// #include <QNetworkRequest>
// #include <QNetworkReply>


struct MRequestData;
struct MResponseData
{
	QByteArray data;
	QJsonObject root;
	int status;
	MRequestData *request;
	void *other;
};

struct MRequestData
{
	QString url;
	QByteArray data;
	std::function<void(int, const MResponseData &)> callback;
	bool auth;
	void *other;
};



class MHttp : public QObject
{
	Q_OBJECT

public:
	MHttp(QObject *parent=nullptr);
	~MHttp();

	void post(const QString &url, 
		const QJsonObject &data, 
		std::function<void(int, const MResponseData &)> callback,
		bool auth = true,
		void *other = NULL
		);
	void post(const QString &url, 
		const QByteArray &data, 
		std::function<void(int, const MResponseData &)> callback,
		bool auth = true,
		void *other = NULL
		);

	void postImage(const QString &url, 
		const QByteArray &data, 
		std::function<void(int, const MResponseData &)> callback,
		bool auth = true);
	void setToken(const QString &token);

private:
	QByteArray makeMultipart(const QByteArray &boundary, const QByteArray &data, const QByteArray &md5);

private:
	void refreshTokenCallback(int status, const MResponseData &data);
private slots:
	void replayFinished(QNetworkReply *reply);

private:
	QNetworkAccessManager *m_manager;
	int m_count;
	std::map<int, MRequestData> m_cbMap;
	QString m_token;
	bool m_waitTokenUpdate;
	std::vector<MRequestData> m_waitList;
	QString m_hostUrl;
};
